package com.example.leetdemo.consistenthash;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.SortedMap;
import java.util.TreeMap;

public class MultiRateHash {


    public static void main(String[] args) {
        String params = "[{\"rate\":2,\"time\":\"08:00\"},{\"rate\":1,\"time\":\"09:00\"},{\"rate\":4,\"time\":\"11:00\"},{\"rate\":2,\"time\":\"13:00\"},{\"rate\":1,\"time\":\"15:00\"},{\"rate\":2,\"time\":\"17:00\"},{\"rate\":4,\"time\":\"22:00\"}]";
        JSONArray jsonArray = JSONArray.parseArray(params);
        for (int i = 0; i < 24; i++) {
            String time = i + ":" + "00";
            if (i < 10) {
                time = "0" + time;
            }
            time = "2023-04-19 " + time;
            System.err.println(time + "       " + getRate(time, jsonArray));
        }
//        System.err.println(getRate("2023-04-19 08:00", jsonArray));
    }

    private static Integer getRate(String beginTime, JSONArray params) {
        if (params == null || params.size() == 0) {
            return 0;
        }
        String date = beginTime.substring(11, 16);
        Integer rate;
        // 存放日期和日时刻编号的对应关系
        SortedMap<String, Integer> sortedMap = new TreeMap<>();
        for (Object object : params) {
            JSONObject param = (JSONObject) object;
            // 历史遗留问题 有的没有choose字段 选定配置成功的param
            if (param.getBoolean("choose") == null || param.getBoolean("choose")) {
                sortedMap.put(param.getString("time"), param.getInteger("rate"));
            }
        }
        if (sortedMap.containsKey(date)) {
            return sortedMap.get(date);
        }
        SortedMap<String, Integer> thisSort = sortedMap.headMap(date);
        if (thisSort.size() == 0) {
            rate = sortedMap.get(sortedMap.lastKey());
        } else {
            rate = sortedMap.get(thisSort.lastKey());
        }
        return rate;


//        SortedMap<String, Integer> thisSort = sortedMap.tailMap(date);
//        if (thisSort.size() == 0) {
//            rate = sortedMap.get(sortedMap.firstKey());
//        } else {
//            rate = sortedMap.get(thisSort.firstKey());
//        }
//        return rate;

    }
}
